package cn.walls1717.wallsmall.member.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置类
 *
 * @author walls1717
 * @since 2022/11/19 11:12
 **/
@Configuration
public class FeignConfig {

    /**
     * Feign请求拦截器<br>
     * Feign请求到达远程服务之前，会先经过此拦截器。
     *
     * @return 请求拦截器
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // 获取老请求属性
            ServletRequestAttributes attributes =
                ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes());

            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                // 获取老请求的cookie
                String cookie = request.getHeader("Cookie");
                // 给新请求设置请求头
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
